iT邦幫忙

2024 iThome 鐵人賽

DAY 13
0
佛心分享-刷題不只是刷題

CPE C++ 刷題系列 第 13

CPE C++ 刷題 Day 13

  • 分享至 

  • xImage
  •  

今天來解YKL13(UVA10929):You can say 11

You can say 11

https://ithelp.ithome.com.tw/upload/images/20240927/20155574fFp5sq5WFK.png
要則麼確認是不是 11 的倍數
=>奇數位數字和與偶數位數字和的差為0或11的倍數

這題不能用int去解,所以我用了string
odd += N[i] - '0';
這裡不能用int()
因為int()是將字元轉換為對應的ASCII值,而不是數字。
ex: '1' => 49

解決方法就是用N[i] - '0'
'1' - '0' = 49 - 48 = 1
'2' - '0' = 50 - 48 = 2
'3' - '0' = 51 - 48 = 3

#include <bits/stdc++.h>

using namespace std;

int main(){
	string N;
	while(cin >> N){
		int odd=0;
		int even=0;
		if(N == "0"){
			continue;
		}
		for(int i=0;i<N.size();i++){
			if(i%2==1){
				odd += N[i] - '0';
			}else{
				even += N[i] - '0';
			}
		}
		int results = abs(odd - even);
		
		if(results%11==0){
			cout << N << " is a multiple of 11." << endl;
		}else{
			cout << N << " is not a multiple of 11." << endl;
		}
	}
	return 0;
}

上一篇
CPE C++ 刷題 Day 12
下一篇
CPE C++ 刷題 Day 14
系列文
CPE C++ 刷題20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言